jQuery.cookie=function(name,value,options){
    if(typeof value!='undefined'){
        options=options||{};
        if(value===null){
            value='';
            options.expires=-1;
        }
        var expires='';
        if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){
             var date;
            if(typeof options.expires=='number'){
                date=new Date();
                date.setTime(date.getTime()+(options.expires * 24 * 60 * 60 * 1000));
             }else{
                date=options.expires;
            }
            expires=';expires='+date.toUTCString();
         }
        var path=options.path?';path='+options.path:'';
        var domain=options.domain?';domain='+options.domain:'';
        var secure=options.secure?';secure':'';
        document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');
     }else{
        var cookieValue=null;
        if(document.cookie&&document.cookie!=''){
            var cookies=document.cookie.split(';');
            for(var i=0;i<cookies.length;i++){
                var cookie=jQuery.trim(cookies[i]);
                if(cookie.substring(0,name.length+1)==(name+'=')){
                    cookieValue=decodeURIComponent(cookie.substring(name.length+1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(function() {
    // select style theme
    $('.J-select-theme a.css-style').click(function(){
        $.cookie('css_style', $(this).data('style'), { path: '/'});
        location.reload();
    });

    $('[data-toggle="tooltip"]').tooltip();

    GVar.slideToTop();
});

Array.prototype.in_array = function(e)
{
  for(var i=0;i<this.length && this[i]!=e;i++){}
  return !(i==this.length);
};

// GVar
window.GVar = window.GVar || {};

GVar.lcfirst = function(str) {
    return str.substr(0,1).toLowerCase() + str.slice(1);
};
GVar.ucfirst = function(str) {
    return str.substr(0,1).toUpperCase() + str.slice(1);
};
GVar.toJson = function (_form) {
    // to json object
    return JSON.parse(JSON.stringify(_form));
};
GVar.closeAlert = function (box) {
    var box = typeof box == 'string' ? $(box) : box;
    box.html('');
};
GVar.showAlert = function (box, args) {
  var args = $.extend({
        type: 'warning',// info success primary danger
        title:'Warning!',
        msg:'',
        onlyOne: true,
        enableClose:true
      }, args),
      box = typeof box == 'string' ? $(box) : box;
  var button = '';
  if ( args.enableClose ) {
    button = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
  }
  var html = '<div class="alert alert-' + args.type + ' alert-dismissible" role="alert">'
      + button
      +'<strong>' + args.title + '</strong>' + args.msg
      +'</div>';

  if ( !box[0] ) {
    console.error('target box element don\'t exists!');
    return false;
  }

  args.onlyOne ? box.html(html) : box.append(html);

  return true;
};
GVar.slideToTop = function () {
    var slideToTop = $("<div />");
    slideToTop.html('<i class="glyphicon glyphicon-chevron-up"></i>');
    slideToTop.css({
      position: 'fixed',
      bottom: '20px',
      right: '25px',
      width: '40px',
      height: '40px',
      color: '#eee',
      'font-size': '',
      'line-height': '40px',
      'text-align': 'center',
      'background-color': '#222d32',
      cursor: 'pointer',
      'border-radius': '5px',
      'z-index': '99999',
      opacity: '.7',
      'display': 'none'
    });
    slideToTop.on('mouseenter', function () {
      $(this).css('opacity', '1');
    });
    slideToTop.on('mouseout', function () {
      $(this).css('opacity', '.7');
    });
    $('.wrapper').append(slideToTop);
    $(window).scroll(function () {
      if ($(window).scrollTop() >= 150) {
        if (!$(slideToTop).is(':visible')) {
          $(slideToTop).fadeIn(500);
        }
      } else {
        $(slideToTop).fadeOut(500);
      }
    });
    $(slideToTop).click(function () {
      $("body").animate({
        scrollTop: 0
      }, 500);
    });
};
GVar.collectCsrf = function()
{
  return {
    csrf_name : document.getElementById('csrf_name').value,
    csrf_value : document.getElementById('csrf_value').value
  }
};

GVar.pageControl = function(){
  $('#page-control .catelog-control-btn').unbind('click').click(function(){
    var pc = $('#page-container');
     // show
    if( pc.hasClass('sidebar-closed') ) {
      pc.removeClass('sidebar-closed');
    } else {
      pc.addClass('sidebar-closed')
    }
  });

  $('#page-control .content-control-btn').unbind('click').click(function(){
    $('#page-control .content-control-tool').toggle();
  });
};

GVar.controlFontSize = function (box, type) {
  var _type = !!type,
    currSize = box.css('font-size'),
    realSize = currSize.substr(0, currSize.length - 2) * 1;

    // enlarge font
    if (type && realSize < 30) {
      box.css('font-size', (realSize + 2) + 'px' );

    } else if (!type && realSize > 8) {
      box.css('font-size', (realSize - 2) + 'px' );
    }
};

// set the content title
GVar.contentTitleHandle = function (contentBox) {
  var h1 = contentBox.find('h1'),
      titleTag = $('head>title'),
      title = $('.article-title');

  var h1Text = h1.first().text();

  // set page title
  if (!titleTag.text().trim()) {
    titleTag.text( h1Text + titleTag.text());
  }

  // content title
  if ( !title.text().trim() && h1[0]) {
    title.text( h1Text );
    h1.first().remove();
  }

  return this;
};

  // content toc
GVar.makeTOC = function(contentBox){
  if (!GVar.pageData.makeTOC) {
    return this;
  }

  var tocList = $("#content-toc-list"),
      tocBox = $('#content-toc-box'),
      hList = contentBox.find("h2,h3,h4,h5,h6");

  if ( !hList[0] ) {
    tocBox.remove();

    return this;
  }

  hList.each(function(i,item){
    var tag = $(item).get(0).localName;

    $(item).attr("id","wow_"+i);
    tocList.append('<a class="toc-'+tag+'" href="#wow_'+i+'">'+$(this).text()+'</a></br>');
    tocList.find(".toc-h2").css("margin-left",0);
    tocList.find(".toc-h3").css("margin-left",15);
    tocList.find(".toc-h4").css("margin-left",30);
    tocList.find(".toc-h5").css("margin-left",45);
    tocList.find(".toc-h6").css("margin-left",60);
  });

  tocBox.show().find('small').on('click',function(){
    var icon = $(this).find('i');

    $('#content-toc').toggle('slow', function() {
      if ( icon.hasClass('glyphicon-chevron-up') ) {
        icon.removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
      } else {
        icon.removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
      }
    });
  });

  return this;
};

// path: /redis/audio-book.md
// suffix 后缀，要带点 e.g: .md
GVar.clearSuffix = function(path, suffix) {
  var sLen = suffix.length;

  if ( path.substr(-sLen) == suffix ) {
    path = path.substr(0, path.length - sLen);
  }

  return path;
};